/*
 * @Author: 胡海
 * @Date: 2020-02-21 18:23:26
 * @LastEditors: 胡海
 * @LastEditTime: 2020-03-07 21:17:44
 * @Description: 
 */
const {
    sequelize
} = require('../../core/db.js')


const {
    Sequelize,
    Model,
    Op
} = require('sequelize')

const {
    isOptionalObj
} = require('../../app/libs/util')

// define
class Fund extends Model {
    // 业务表
    static async listFund(ctx, v) { // 列表
        let request = {
            p: v.get('body.p'),
            count: v.get('body.count'),
            start: v.get('body.start'),
        }
        const total = await Fund.count()
        const list = await Fund.findAll({
            where: {
                incomeName: {
                    [Op.like]: `%${request.p}%`
                },
            },
            order: [
                ['id']
            ],
            limit: request.count,
            offset: (request.start - 1) * request.count,
        })
        const data = {
            list,
            total
        }
        return data
    }
    static async addFund(ctx, v) { // 新增
        let request = {
            incomeName: v.get('body.incomeName'),
            buyPrice: v.get('body.buyPrice'),
        }
        const info = await Fund.findOne({
            where: {
                incomeName: v.get('body.incomeName'),
            }
        })
        if (info) {
            throw new global.errs.LikeError('基金已存在')
        }
        await Fund.create(request)
        throw new global.errs.Success()
    }
    static async delFund(ctx, v) { // 删除
        const info = await Fund.destroy({
            where: {
                id: v.get('body.id')
            }
        })
        throw new global.errs.Success()
    }
    static async editFund(ctx, v) { // 修改
        let request = {
            incomeName: v.get('body.incomeName'),
            buyPrice: v.get('body.buyPrice'),
            dropPrice: v.get('body.dropPrice'),
        }
        let data = isOptionalObj(request)
        const info = await Fund.update(data, {
            where: {
                id: v.get('body.id')
            }
        })
        throw new global.errs.Success()
    }
}

Fund.init({
    incomeName: Sequelize.STRING,
    buyPrice: Sequelize.STRING,
    dropPrice: Sequelize.INTEGER,
}, {
    sequelize,
    tableName: 'fund',
    alter: true
})

module.exports = {
    Fund
}

// 数据迁移 SQL 更新 风险